Page({
  data: {
    recipeData: {}, // 存储动态获取的菜谱详情数据
    comments: [],   // 评论数据
    newComment: "", // 新评论内容
    hasCommented: false, // 是否已评论
    showModal: false, // 弹窗显示状态
    modalText: "", // 弹窗文本
    modalIcon: "", // 弹窗图标
    loading: true, // 加载状态
    error: false // 错误状态
  },

  onLoad: function (options) {
    const recipeId = options.id;
    this.loadRecipeData(recipeId);
    this.loadComments(recipeId);
  },

  // 加载菜谱详情数据
  loadRecipeData: function (recipeId) {
    this.setData({
      loading: true,
      error: false
    });

    let token = '';
    try {
      token = wx.getStorageSync('token');
      console.log('获取到的token:', token);
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    wx.request({
      url: `http://localhost/dev-api/recipes/recipes/${recipeId}`, // 路径风格：/recipes/recipes/1
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        wx.hideLoading();

        if (res.data.code === 200 && res.data.rows.length > 0) {
          const recipe = res.data.rows[0];
          // 数据映射，将后端返回数据转换为页面所需格式
          const mappedRecipe = {
            id: recipe.id,
            title: recipe.title,
            image: recipe.coverUrl 
              ? `http://localhost${recipe.coverUrl}` 
              : 'https://picsum.photos/400/300?random=default',
            time: recipe.cookTimeOptions?.name || '未知时间',
            difficulty: recipe.difficultyOptions?.name || '未知难度',
            collections: recipe.collectCount || 0,
            createDate: recipe.createTime ? recipe.createTime.split(' ')[0] : '未知日期',
            viewCount: recipe.viewCount + '次',
            author: {
              id: recipe.userId,
              name: recipe.users?.nickname || '未知作者',
              avatar: recipe.users?.avatarUrl || 'https://picsum.photos/100/100?random=author',
              gender: '',
              joinYear: '',
              isFollowed: false,
              otherRecipes: [] // 可根据实际接口补充其他菜谱数据
            },
            ingredients: recipe.recipeIngredients?.map(ing => ({
              name: ing.name,
              amount: `${ing.quantity}${ing.unit}`
            })) || [],
            steps: recipe.recipeSteps?.map(step => ({
              image: step.coverImg 
                ? `http://localhost${step.coverImg}` 
                : 'https://picsum.photos/400/300?random=step',
              instructions: [step.content]
            })) || []
          };

          this.setData({
            recipeData: mappedRecipe,
            loading: false
          });
        } else {
          this.setData({
            error: true,
            loading: false
          });
          wx.showToast({
            title: '菜谱数据加载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        this.setData({
          error: true,
          loading: false
        });
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  // 加载评论数据（示例，需根据实际评论接口调整）
  loadComments: function (recipeId) {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.request({
      url: 'http://localhost/dev-api/recipes/comments/list', 
      method: 'GET',
      data: {
        recipeId: recipeId
      },
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 数据映射，将后端评论数据转换为页面所需格式
          const mappedComments = (res.data.rows || []).map(comment => ({
            id: comment.id,
            userName: comment.user?.nickname || '未知用户',
            userAvatar: comment.user?.avatarUrl || 'https://picsum.photos/60/60?random=user',
            content: comment.content,
            date: comment.createTime ? comment.createTime.split(' ')[0] : '未知日期',
            likeCount: comment.likeCount || 0,
            isLiked: false
          }));

          this.setData({
            comments: mappedComments
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '评论数据加载失败',
          icon: 'none'
        });
      }
    });
  },

  // 跳转到用户详情页
  goToUserDetail: function () {
    wx.navigateTo({
      url: '/pages/user/user?id=' + this.data.recipeData.author.id
    });
  },

  // 切换关注状态
  toggleFollow: function () {
    const isFollowed = this.data.recipeData.author.isFollowed;
    const newFollowState = !isFollowed;

    this.setData({
      'recipeData.author.isFollowed': newFollowState
    });

    this.showModalMessage(
      newFollowState ? "关注成功" : "取消关注",
      newFollowState ? "✅" : "❌"
    );

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      return;
    }

    wx.request({
      url: 'http://localhost/dev-api/user/follow',
      method: 'POST',
      data: {
        userId: this.data.userInfo?.id || 999,
        authorId: this.data.recipeData.author.id,
        action: newFollowState ? 'follow' : 'unfollow'
      },
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      }
    });
  },

  // 评论输入
  onCommentInput: function (e) {
    this.setData({
      newComment: e.detail.value
    });
  },

  // 提交评论
  submitComment: function () {
    if (!this.data.newComment.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none'
      });
      return;
    }

    if (this.data.hasCommented) {
      this.showModalMessage("已经评论过了", "⚠️");
      return;
    }

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      wx.showToast({
        title: '授权异常',
        icon: 'none'
      });
      return;
    }

    const newComment = {
      id: Date.now(),
      userName: this.data.userInfo?.name || '当前用户',
      userAvatar: this.data.userInfo?.avatar || 'https://picsum.photos/60/60?random=current',
      content: this.data.newComment,
      date: this.formatDate(new Date()),
      likeCount: 0,
      isLiked: false
    };

    const comments = [newComment, ...this.data.comments];

    this.setData({
      comments: comments,
      newComment: "",
      hasCommented: true
    });

    wx.request({
      url: 'http://localhost/dev-api/recipes/comments/submit',
      method: 'POST',
      data: {
        recipeId: this.data.recipeData.id,
        userId: this.data.userInfo?.id || 999,
        content: newComment.content
      },
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      }
    });
  },

  // 切换点赞状态
  toggleLike: function (e) {
    const commentId = e.currentTarget.dataset.id;
    const comments = this.data.comments;
    const commentIndex = comments.findIndex(item => item.id === commentId);

    if (commentIndex === -1) return;

    const comment = comments[commentIndex];
    const newLikeState = !comment.isLiked;
    const newLikeCount = newLikeState ? comment.likeCount + 1 : comment.likeCount - 1;

    comments[commentIndex] = {
      ...comment,
      isLiked: newLikeState,
      likeCount: newLikeCount
    };

    this.setData({
      comments: comments
    });

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
      return;
    }

    wx.request({
      url: 'http://localhost/dev-api/recipes/comments/like',
      method: 'POST',
      data: {
        commentId: commentId,
        userId: this.data.userInfo?.id || 999,
        action: newLikeState ? 'like' : 'unlike'
      },
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      }
    });
  },

  // 显示弹窗消息
  showModalMessage: function (text, icon) {
    this.setData({
      showModal: true,
      modalText: text,
      modalIcon: icon
    });

    setTimeout(() => {
      this.hideModal();
    }, 3000);
  },

  // 隐藏弹窗
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },

  // 阻止事件冒泡
  stopPropagation: function () {
    // 空函数，用于阻止事件冒泡
  },

  // 格式化日期
  formatDate: function (date) {
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${month}-${day}`;
  },

  // 页面分享
  onShareAppMessage: function () {
    return {
      title: this.data.recipeData.title,
      path: '/pages/recipe/recipe?id=' + this.data.recipeData.id
    };
  }
});